﻿package com.snzflash.components.scroll 
{
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Rectangle;
	import org.casalib.display.CasaSprite;
	
	/**
	 * Базовый класс для скролла
	 * @author firsoff maxim, tel: +79222345364, skype: maxim.firsoff
	 */
	public class Scroll extends CasaSprite
	{
		// тумбаляшка
		public var thumb:MovieClip;
		// фон
		public var background:MovieClip;
		// позиция
		protected var _position:Number = 0;
		// прямоугольник для скролла
		protected var _scrollableRect:Rectangle;
		
		public function Scroll() 
		{
			super();
			init();
		}
		
		override public function destroy():void 
		{
			super.destroy();
			if ( destroyed ) return;
			thumb.stopDrag();
			//removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
			//removeEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage);
			thumb.removeEventListener(MouseEvent.MOUSE_DOWN, onThumbMouseDown);
			stage.removeEventListener(MouseEvent.MOUSE_UP, onStageUp);
			stage.removeEventListener(MouseEvent.MOUSE_MOVE, onStageMove);
		}
		
		protected function init():void 
		{
			addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
			addEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage);
			position = 0;
			////trace('init');
		}
		
		protected function setPosition():void
		{
			
		};
		
		
		
		protected function onThumbMouseDown(event:MouseEvent):void 
		{
			stage.addEventListener(MouseEvent.MOUSE_UP, onStageUp);
			stage.addEventListener(MouseEvent.MOUSE_MOVE, onStageMove);
			////trace('onThumbMouseDown');
		};
		
		protected function onStageMove(event:MouseEvent):void 
		{
			event.updateAfterEvent();
			setPosition();
			dispatchEvent(new Event(Event.CHANGE));
		};
		
		protected function onStageUp(event:MouseEvent):void 
		{
			////trace('onStageUp');
			thumb.stopDrag();
			stage.removeEventListener(MouseEvent.MOUSE_MOVE, onStageMove);
			stage.removeEventListener(MouseEvent.MOUSE_UP, onStageUp)
		};
		
		protected function onRemovedFromStage(event:Event):void 
		{
			removeEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage);
		};
		
		protected function onAddedToStage(event:Event):void 
		{
			thumb.addEventListener(MouseEvent.MOUSE_DOWN, onThumbMouseDown);
			thumb.buttonMode = true;
			removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
		};
		
		public function get position():Number { return _position; };
		
		public function set position(value:Number):void 
		{
			value = value > 1 ? 1 : value < 0 ? 0 : value;
			_position = value;
		};
		
	}

}